'''
eg:
exec_onecmd('192.168.75.124','root','123456','ifconfig')
exec_multicmd('192.168.75.124','root','123456','cd /home','ls -l')
exec_cmdlist('192.168.75.124','root','123456',['cd /home','ls -l'])

ssh1 = SSH('192.168.75.124','root','123456')
ssh1.exec_onecmd('ifconfig')
ssh1.exec_multicmd('ls l','ifconfig')
ssh1.exec_cmdlist(['cd /home','ls -l'])

ftp1 = FTP('192.168.75.124','root','123456')
ftp1.upload('123.py','/home/123.py')
ftp1.download('123.py','/home/123.py')

newstr1 = list_to_cmd(['cd /home', 'ls -l'])
newstr2 = multistr_to_cmd('cd /home', 'ls -l')
'''

# windows/linux--py2/3 均支持
import paramiko
import os

mycmd = 'ls -l /home/moocos'
hostaddr = '192.168.75.124'
port = 22
uname = 'moocos'
pwd = ' '


def exec_onecmd(hostaddr, username, password, cmd):
    s = paramiko.SSHClient()
    # 读取know_host
    s.load_system_host_keys()
    # 建立SSH连接
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostaddr, 22, username, password)
    stdin, stdout, stderr = s.exec_command(cmd)
    for x in stdout.readlines():
        print(x.strip())
    s.close()


def exec_multicmd(hostaddr, username, password, *cmds):
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostaddr, 22, username, password)
    for cmd in cmds:
        stdin, stdout, stderr = s.exec_command(cmd)
        for x in stdout.readlines():
            print(x.strip())
    s.close()


def exec_cmdlist(hostaddr, username, password, cmdlist):
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostaddr, 22, username, password)
    for cmd in cmdlist:
        stdin, stdout, stderr = s.exec_command(cmd)
        for x in stdout.readlines():
            print(x.strip())
    s.close()


def list_to_cmd(strlist):
    temp_str = ''
    for x in strlist:
        temp_str = temp_str + x +';'
    return temp_str


def multistr_to_cmd(*strs):
    temp_str = ''
    for x in strs:
        temp_str = temp_str + x +';'
    return temp_str




class FTP():
    def __init__(self, hostaddr, username, password):
        super(FTP, self).__init__()
        self.__trans = paramiko.Transport((hostaddr, 22))
        self.__trans.connect(username=username, password=password)
        self.sftp = paramiko.SFTPClient.from_transport(self.__trans)

    def __del__(self):
        self.__trans.close()

    # 递归获取本地某文件夹下所有文件的完整路径
    def get_allfiles_in_localdir(self, localdir):
        allfiles = []
        files = os.listdir(localdir)
        for x in files:
            filename = os.path.join(localdir, x)
            if os.path.isdir(filename):
                allfiles.extend(self.get_allfiles_in_localdir(filename))
            else:
                allfiles.append(filename)
        return allfiles

    def upload_one(self, fromfile, tofile):
        self.sftp.put(localpath=fromfile, remotepath=tofile)

    def download_one(self, fromfile, tofile):
        self.sftp.get(localpath=fromfile, remotepath=tofile)

    # 上传dir下所有文件包括子目录里, 但这些文件最后堆一起, 没有分文件夹放
    def upload_dir(self, localdir, remotedir):
        if remotedir[-1] == '/':        # 去掉路径最后的'/', 如果有的话
            remotedir = remotedir[0:-1]
        allfiles = self.get_allfiles_in_localdir(localdir)
        for fullpath in allfiles:
            filename = os.path.split(fullpath)[-1]
            remote_fullpath = remotedir + '/' + filename
            print('传输成功:' + filename)
            self.upload_one(fullpath, remote_fullpath)

    def close(self):
        self.__trans.close()


class SSH():
    def __init__(self, hostaddr, username, password):
        super(SSH, self).__init__()
        self.sshclient = paramiko.SSHClient()
        self.sshclient.load_system_host_keys()
        self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.sshclient.connect(hostaddr, 22, username, password)

    def __del__(self):
        self.sshclient.close()

    def exec_onecmd(self, cmd):
        stdin, stdout, stderr = self.sshclient.exec_command(cmd)
        for x in stdout.readlines():
            print(x.strip())

    def exec_multicmd(self, *cmds):
        for cmd in cmds:
            stdin, stdout, stderr = self.sshclient.exec_command(cmd)
            for x in stdout.readlines():
                print(x.strip())

    def exec_cmdlist(self, cmdlist):
        for cmd in cmdlist:
            stdin, stdout, stderr = self.sshclient.exec_command(cmd)
            for x in stdout.readlines():
                print(x.strip())

    def close(self):
        self.sshclient.close()


if __name__ == '__main__':
    # exec_onecmd(hostaddr,uname,pwd,mycmd)
    # exec_multicmd(hostaddr,uname,pwd,mycmd,'ifconfig')

    # cmdlist = []
    # cmdlist.append(mycmd)
    # cmdlist.append('ifconfig')
    # exec_cmdlist(hostaddr,uname,pwd,cmdlist)

    # ssh1 = SSH('39.108.226.252', 'root', '123qwert/')
    # ssh1.exec_multicmd('ls -l /home')

    # ftps = FTP('39.108.226.252', 'root', '123qwert/')
    # ftps.upload_dir(r'F:\py_test', '/home/123')
    print('This is paramiko module by shuoGG')
